/*
 * Copyright (c) 2009-2013 EvTech Project
 * All rights reserved.
 * 
 * This file is part of Game packet.
 *
 * Game packet is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or 
 * (at your option) any later version.
 *
 * Game packet is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Game packet.  If not, see <http://www.gnu.org/licenses/>.
 * 
 */
package fi.honkalampisaatio.sound;

import java.util.Random;

import javax.sound.midi.MidiChannel;
import javax.sound.midi.MidiSystem;
import javax.sound.midi.MidiUnavailableException;
import javax.sound.midi.Synthesizer;

public class MidiNotePlayer {

	public static MidiNotePlayer INSTANCE;
	
	public static MidiNotePlayer getInstance() throws MidiUnavailableException {
		if (INSTANCE == null) {
			INSTANCE = new MidiNotePlayer();
		}
		return INSTANCE;
	}
	
	
	private Synthesizer synth; 
	private MidiChannel channel;
	
	private int note = 60;
	
	private int[] c_scale = {60,62,64,65,67,69,71,72};
	
	private Random rnd = new Random();
	
	protected MidiNotePlayer() throws MidiUnavailableException{

		synth = MidiSystem.getSynthesizer();
		synth.open();
		channel = synth.getChannels()[0];

	}
	
	public int playRandomCScaleNote() {
		int tn = c_scale[this.rnd.nextInt(c_scale.length)];
		this.playNote(tn);
		return tn;
	}
	
	public void playNote(int note) {
	      // Create a new thread
		this.note = note;
	      Thread noteThread =  new Thread() {
	         // Override run() to provide the running behavior of this thread.
	         @Override
	         public void run() {
	            _notePlay();
	         }
	      };
	      // Start the thread. start() calls run(), which in turn calls gameLoop().
	      noteThread.start();		
	}
	
	private void _notePlay() {
		int note = this.note;
        channel.noteOn(note, 90);
       
        
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
           e.printStackTrace();
        } finally {
            channel.noteOff(note);
        }		
	}

	
	protected void finalize() {
		if (this.synth != null)
			synth.close();
	}
	
	public static void main(String[] args) {
		
		try {
			MidiNotePlayer mnp = new MidiNotePlayer();
			mnp.playNote(60);
		} catch (MidiUnavailableException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
}
